const app = getApp()
Component({
  properties: {
    img_url: {
      type: String,
      value: '/images/index.png',
    },
    out_height: {
      type: Number,
      value: 630
    }
  },
  data: {
    tempCanvasWidth: 0,
    tempCanvasHeight: 0,
    imgViewHeight: 0,
    page: 'cropPage',
    minScale: 0.5,
    maxScale: 2.5,
    tempImageSrc: '',
    imgWidth: 0,
    imgHeight: 0,
    imgTop: 0,
    imgLeft: 0,
    // 裁剪框 宽高
    cutW: 0,
    cutH: 0,
    cutL: 0,
    cutT: 0,
    deviceRatio: 0,

    isdiscerning: false,
    croped: false,
    outer_top_margin: 0,
    out_height: 0,
    imageView: 'height:90vh',

    animation: '',
    rotateTime: 0,
    originimgWidth: 0,
    originimgHeight: 0,
    originimgTop: 0,
    originimgLeft: 0,
    rotateDeg: 90,
  },
  mydata: {
    pageparam: {},
    dragLengthX: 0,
    dragLengthY: 0,
    minCutL: 0,
    minCutT: 0,
    maxCutL: 0,
    maxCutT: 0,
    newCutL: 0,
    newCutT: 0,
    showcanvas: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  attached: function () {
    let self = this
    let options = {};
    options.imagepath = this.properties.img_url?this.properties.img_url:'/images/index.png';
    self.imgViewHeight = this.properties.out_height;
    self.device = app.globalData.myDevice
    self.windowWidth = app.globalData.myDevice.windowWidth
    self.deviceRatio = app.globalData.myDevice.windowWidth / 750

    self.setData({
      imgViewHeight: self.imgViewHeight,
    })
  
    this.createSelectorQuery().select('#imageView').boundingClientRect(function (rect) {
      self.data.outer_top_margin = rect.top;
      self.data.out_height = rect.height;
      self.chooseImage(options)
    }).exec()
  },
  ready: function() {
    this.animation = wx.createAnimation({
      duration: 600,
      timingFunction: 'ease-in-out'
    })
  },
  observers: {
    'img_url, out_height': function(img_url, out_height){
      console.log('初始化',img_url,out_height)
      // console.log(this)
      let options={};
      options.imagepath = img_url;
      this.imgViewHeight = out_height;
      if(!this.animation){
        this.animation = wx.createAnimation({
          duration: 600,
          timingFunction: 'ease-in-out'
        })
      }
      this.animation.rotate(0).step();
 
      this.setData({
        imgViewHeight: out_height,
        animation: this.animation.export()
      })
      
      // this.data.out_height = out_height;
      // console.log(this.data.imgViewHeight)
      this.chooseImage(options)
    }
  },
  methods: {
    croperStart(e) {
      this.croperX = e.touches[0].clientX
      this.croperY = e.touches[0].clientY
      this.moveStartX= e.touches[0].clientX
      this.moveStartY= e.touches[0].clientY
    },
    croperMove(e) {
      var self = this
      var dragLengthX = (e.touches[0].clientX - self.croperX)
      var dragLengthY = (e.touches[0].clientY - self.croperY)
      var minCutL = Math.max(0, self.data.imgLeft)
      var minCutT = Math.max(0, self.data.imgTop)
      var maxCutL = Math.min(750 * self.deviceRatio - self.data.cutW, self.data.imgLeft + self.data.imgWidth - self.data.cutW)
      var maxCutT = Math.min(self.imgViewHeight - self.data.cutH, self.data.imgTop + self.data.imgHeight - self.data.cutH)
      var newCutL = self.data.cutL + dragLengthX
      var newCutT = self.data.cutT + dragLengthY
      if (newCutL < minCutL) newCutL = minCutL
      if (newCutL > maxCutL) newCutL = maxCutL
      if (newCutT < minCutT) newCutT = minCutT
      if (newCutT > maxCutT) newCutT = maxCutT
      this.setData({
        cutL: newCutL,
        cutT: newCutT,
      })
      self.croperX = e.touches[0].clientX
      self.croperY = e.touches[0].clientY
    },
    croperMoveEnd(e){
      let endX=e.changedTouches[0].clientX
      let endY=e.changedTouches[0].clientY
      if(Math.abs(this.moveStartX-endX)>5||Math.abs(this.moveStartY-endY)>5){
        this.triggerEvent('cropChange')
      }
    },
    dragPointStart(e) {
      this.dragStartX = e.touches[0].clientX
      this.dragStartY = e.touches[0].clientY
      this.initDragCutW = this.data.cutW
      this.initDragCutH = this.data.cutH
      this.initDragCutL = this.data.cutL
      this.initDragCutT = this.data.cutT
      this.moveStartX=e.touches[0].clientX
      this.moveStartY=e.touches[0].clientY
    },
    dragPointMove(e) {
      this.maxDragX = this.data.imgLeft + this.data.imgWidth;
      this.maxDragY = this.data.imgTop + this.data.outer_top_margin + this.data.imgHeight;
      this.dragMoveX = Math.min(e.touches[0].clientX, this.maxDragX);
      this.dragMoveY = Math.min(e.touches[0].clientY, this.maxDragY);
      this.dragLengthX = this.dragMoveX - this.dragStartX
      this.dragLengthY = this.dragMoveY - this.dragStartY
      this.dragW = this.initDragCutW + this.dragLengthX > this.data.imgWidth ? this.data.imgWidth : this.initDragCutW + this.dragLengthX
      this.dragH = this.initDragCutH + this.dragLengthY > this.data.imgHeight ? this.data.imgHeight : this.initDragCutH + this.dragLengthY
      this.setData({
        cutW: this.dragW,
        cutH: this.dragH
      })
      this.data.cutW = this.dragW;
      this.data.cutH = this.dragH;
    },
    dragPointMoveTR(e) {
      //页面宽高度下，x轴最大值，y轴最大值
      this.maxDragX = this.data.imgLeft + this.data.imgWidth;
      this.maxDragY = this.data.imgTop + this.data.outer_top_margin + this.data.imgHeight;
      //触点偏移量需小于x轴最大值，y轴最大值
      this.dragMoveX = Math.min(e.touches[0].clientX, this.maxDragX);
      this.dragMoveY = Math.min(e.touches[0].clientY, this.maxDragY);
      //坐标变化量
      this.dragLengthX = this.dragMoveX - this.dragStartX
      this.dragLengthY = this.dragMoveY - this.dragStartY
  
      // 裁剪框可扩展宽高
      this.maxDragWidth = this.data.imgWidth - (this.initDragCutL - this.data.imgLeft);
      this.maxDragHeight = this.initDragCutH + this.initDragCutT - this.data.imgTop;
      // 裁剪框目标宽高与顶部距离
      this.dragW = this.initDragCutW + this.dragLengthX > this.data.imgWidth ? this.data.imgWidth : (this.initDragCutW + this.dragLengthX >= this.maxDragWidth ? this.maxDragWidth : this.initDragCutW + this.dragLengthX)
  
      this.dragH = this.initDragCutH - this.dragLengthY > this.data.imgHeight ? this.data.imgHeight : (this.initDragCutH - this.dragLengthY >= this.maxDragHeight ? this.maxDragHeight : this.initDragCutH - this.dragLengthY)
      this.dragTop = this.initDragCutT + this.dragLengthY < this.data.imgTop ? this.data.imgTop : this.initDragCutT + this.dragLengthY;
      this.setData({
        cutW: this.dragW,
        cutH: this.dragH,
        cutT: this.dragTop
      })
    },
    dragPointMoveBL(e) {
      this.maxDragX = this.data.imgLeft + this.data.imgWidth;
      this.maxDragY = this.data.imgTop + this.data.outer_top_margin + this.data.imgHeight;
      this.dragMoveX = Math.min(e.touches[0].clientX, this.maxDragX);
      this.dragMoveY = Math.min(e.touches[0].clientY, this.maxDragY);
      this.dragLengthX = this.dragMoveX - this.dragStartX
      this.dragLengthY = this.dragMoveY - this.dragStartY
      // 裁剪框可扩展宽高
      this.maxDragWidth = this.initDragCutW + this.initDragCutL - this.data.imgLeft;
      this.maxDragHeight = this.data.imgHeight - (this.initDragCutT - this.data.imgTop);
      // 裁剪框目标宽高与左方距离
      this.dragLeft = this.initDragCutL + this.dragLengthX < this.data.imgLeft ? this.data.imgLeft : this.initDragCutL + this.dragLengthX;
      this.dragW = this.initDragCutW - this.dragLengthX > this.data.imgWidth ? this.data.imgWidth : (this.initDragCutW - this.dragLengthX >= this.maxDragWidth ? this.maxDragWidth : this.initDragCutW - this.dragLengthX)
      this.dragH = this.initDragCutH + this.dragLengthY > this.data.imgHeight ? this.data.imgHeight : (this.initDragCutH + this.dragLengthY >= this.maxDragHeight ? this.maxDragHeight : this.initDragCutH + this.dragLengthY)
      this.setData({
        cutW: this.dragW,
        cutH: this.dragH,
        cutL: this.dragLeft
      })
    },
    dragPointMoveLT(e) {
      this.maxDragX = this.data.imgLeft + this.data.imgWidth;
      this.maxDragY = this.data.imgTop + this.data.outer_top_margin + this.data.imgHeight;
      this.dragMoveX = Math.min(e.touches[0].clientX, this.maxDragX);
      this.dragMoveY = Math.min(e.touches[0].clientY, this.maxDragY);
      this.dragLengthX = this.dragMoveX - this.dragStartX
      this.dragLengthY = this.dragMoveY - this.dragStartY
      // 裁剪框可扩展宽高
      this.maxDragWidth = this.initDragCutW + this.initDragCutL - this.data.imgLeft;
      this.maxDragHeight = this.initDragCutH + this.initDragCutT - this.data.imgTop
      // 裁剪框目标宽高与左方距离与顶部距离
      this.dragLeft = this.initDragCutL + this.dragLengthX < this.data.imgLeft ? this.data.imgLeft : this.initDragCutL + this.dragLengthX;
      this.dragTop = this.initDragCutT + this.dragLengthY < this.data.imgTop ? this.data.imgTop : this.initDragCutT + this.dragLengthY;
      this.dragW = this.initDragCutW - this.dragLengthX > this.data.imgWidth ? this.data.imgWidth : (this.initDragCutW - this.dragLengthX >= this.maxDragWidth ? this.maxDragWidth : this.initDragCutW - this.dragLengthX);
      this.dragH = this.initDragCutH - this.dragLengthY > this.data.imgHeight ? this.data.imgHeight : (this.initDragCutH - this.dragLengthY >= this.maxDragHeight ? this.maxDragHeight : this.initDragCutH - this.dragLengthY);
      this.setData({
        cutW: this.dragW,
        cutH: this.dragH,
        cutL: this.dragLeft,
        cutT: this.dragTop
      })
      this.cutW = this.dragW;
    this.cutH = this.dragH;
    this.cutL = this.dragLeft;
    this.cutT = this.dragTop;
    },
    openCroper() {
      // if(this.imgWidth){
      //   console.log('旋转过');
      //   console.log(this.imgWidth,this.imgHeight);
      //   return
      // }
      var minCutL = Math.max(0, this.data.imgLeft)
      var minCutT = Math.max(0, this.data.imgTop)
      this.setData({
        cutW: this.data.imgWidth,
        cutH: this.data.imgHeight,
        cutL: minCutL,
        cutT: minCutT,
        croped:false
      })
    },
    competeCrop() {
      this.setData({
        showcanvas: true
      })
      let self = this
      wx.showLoading({
        title: '截取中',
        mask: true,
      })
      //图片截取大小
      let ctx = wx.createCanvasContext('tempCanvas',self)
      ctx.clearRect(-15,-15,this.data.tempCanvasWidth+30, this.data.tempCanvasHeight+30)
      // console.log(self.data.tempImageSrc)
      let imgpath;
      imgpath = self.data.tempImageSrc;
      wx.getImageInfo({
        src: self.data.tempImageSrc,
        success(res){
          // imgpath = res.path;
          console.log(res.path)
          // 网络图片转化为本地图片
          if (self.imgWidth) {
            // console.log('旋转过');
            console.log(self.imgWidth, self.imgHeight);
            ctx.translate(self.imgWidth / 2, self.imgHeight / 2);
            console.log(self.deg)
            ctx.rotate(self.deg * Math.PI / 180);
            if ((self.data.rotateTime + 1) % 2 == 0) {
              ctx.drawImage(imgpath, -self.imgHeight / 2, -self.imgWidth / 2, self.imgHeight, self.imgWidth);
            }else{
              ctx.drawImage(imgpath, -self.imgWidth / 2, -self.imgHeight / 2, self.imgWidth, self.imgHeight);
            }
            // console.log(Math.round(self.data.imgWidth), Math.round(self.data.imgHeight))
            // console.log(self.deg)
      
            ctx.translate(-self.imgWidth / 2, -self.imgHeight / 2);
          } else {
            // console.log('没旋转过')
            ctx.drawImage(imgpath, 0, 0, Math.round(self.data.imgWidth), Math.round(self.data.imgHeight))
          }
          ctx.draw(false, function () {
            // self.saveImgUseTempCanvas(100, self.loadImgOnImage())
            setTimeout(() => {
              // console.log(Math.round(self.data.cutW), Math.round(self.data.cutH))
              let cutX = self.data.cutL - self.data.imgLeft;
              let cutY = self.data.cutT - self.data.imgTop;
              let cutW = self.data.cutW;
              let cutH = self.data.cutH;
              console.log(cutX, cutY, cutW, cutH)
              wx.canvasToTempFilePath({
                x: cutX,
                y: cutY,
                width: cutW,
                height: cutH,
                fileType: 'png',
                quality: 1,
                canvasId: 'tempCanvas',
                success: function (res) {
                  wx.hideLoading();
                  console.log(res.tempFilePath)

                  self.setData({
                    tempImageSrc: res.tempFilePath,
                    // croped: true
                  })
                  
                  // self.loadImgOnImage()
                  self.triggerEvent('cropToImgEnd',res.tempFilePath)
                  self.setData({
                    showcanvas: false
                  })
                }
              },self)
            }, 10);
          })
        },
        fail(res){
          // console.log(res)
          wx.showToast({
            title: '解析图片错误',
          })
        }
      })
      //保存图片到临时路径
    },
    chooseImage(options) {
      let self = this;
      var tempFilePaths = options.imagepath
      // console.log(tempFilePaths)
      self.setData({
        tempImageSrc: tempFilePaths
      })
      this.loadImgOnImage()
    },
    loadImgOnImage() {
      let self = this;
      wx.getImageInfo({
        src: self.data.tempImageSrc,
        success: function (res) {
          self.oldScale = 1
          self.initRatio = res.height / (self.imgViewHeight - 40) //转换为了px 图片原始大小/显示大小
          if (self.initRatio < res.width / (self.windowWidth - 40)) { //如果高度比小于宽度比
            self.initRatio = res.width / (self.windowWidth - 40) //设置显示图片与原图片比
          }
          //图片显示大小
          // if (res.width / self.initRatio <= 80 || res.height / self.initRatio <= 80) {
            self.scaleWidth = res.width / self.initRatio
            self.scaleHeight = res.height / self.initRatio
          // } else {
            // scale = 
            // self.scaleWidth = res.width / self.initRatio - 40
            // self.scaleHeight = res.height / self.initRatio - 40
            console.log(self.scaleWidth, self.scaleHeight)
          // }
  
          self.initScaleWidth = self.scaleWidth
          self.initScaleHeight = self.scaleHeight
          self.startX = self.windowWidth / 2 - self.scaleWidth / 2;
          self.startY = self.imgViewHeight / 2 - self.scaleHeight / 2;
          self.setData({
            imgWidth: self.scaleWidth,
            imgHeight: self.scaleHeight,
            imgTop: self.startY,
            imgLeft: self.startX,
            originimgWidth: self.scaleWidth,
            originimgHeight: self.scaleHeight,
            originimgTop: self.startY,
            originimgLeft: self.startX,
            tempCanvasWidth: self.scaleWidth,
            tempCanvasHeight: self.scaleHeight,
          })
          // wx.hideLoading();
          self.openCroper()
        }
      },self)
    },
    // saveImgUseTempCanvas(delay, fn) {
    //   let self = this;
    //   setTimeout(() => {
    //     console.log(Math.round(self.data.cutW), Math.round(self.data.cutH))
    //     let cutX = Math.round(self.data.cutL - self.data.imgLeft);
    //     let cutY = Math.round(self.data.cutT - self.data.imgTop);
    //     console.log(cutX, cutY)
    //     wx.canvasToTempFilePath({
    //       x: cutX,
    //       y: cutY,
    //       width: Math.round(self.data.cutW),
    //       height: Math.round(self.data.cutH),
    //       destWidth: Math.round(self.data.cutW),
    //       destHeight: Math.round(self.data.cutH),
    //       fileType: 'png',
    //       quality: 1,
    //       canvasId: 'tempCanvas',
    //       success: function (res) {
    //         wx.hideLoading();
    //         console.log(res.tempFilePath)
    //         self.setData({
    //           tempImageSrc: res.tempFilePath,
    //           croped: true
    //         })
  
    //         if (fn) {
    //           fn(self, 'crop')
    //         }
    //       }
    //     },self)
    //   }, delay);
    // },
    rotateBeforeMinus() {
      this.data.rotateTime-=1;
      this.deg = this.data.rotateDeg * this.data.rotateTime;
      this.rotate();
    },
    rotateBeforePositive() {
      this.data.rotateTime+=1;
      this.deg = this.data.rotateDeg * this.data.rotateTime;
      this.rotate();
    },
    rotate() {
      let self = this;
      
      console.log(this.data.rotateTime)
      console.log(this.deg)
      //获取缩放比例及缩放后的图片宽高
      if ((Math.abs(this.data.rotateTime)+1) % 2 == 0) {
        console.log('90,270')
        // if(this.data.imgHeight > this.data.imgWidth){
          // this.scaled = (this.windowWidth - 40) / this.data.imgHeight
          // console.log('宽度更小')
        // }else{
          // console.log('高度更小')
          this.scaled = (this.windowWidth - 40) / this.data.imgHeight
          // }
          // 防止出现一柱擎天金箍棒
          if(this.data.originimgWidth * this.scaled >= this.imgViewHeight - 40){
            this.scaled = (this.imgViewHeight - 40) / this.data.imgWidth
          }
        this.imgWidth = this.data.originimgHeight * this.scaled;
        this.imgHeight = this.data.originimgWidth * this.scaled;
      } else {
        this.scaled = 1
        this.imgWidth = this.data.originimgWidth;
        this.imgHeight = this.data.originimgHeight;
        // this.scaledWidth = this.data.imgWidth*(this.data.imgWidth/this.data.imgHeight);
        // this.scaledHeight = this.data.imgWidth;
        // this.scaled = this.windowWidth/this.data.out_height
      }
      // console.log(this.deg, this.scaled)
  
      this.animation.rotate(this.deg).scale(this.scaled).step();
      this.setData({
        animation: this.animation.export()
      })
      this.imgLeft = self.windowWidth / 2 - self.imgWidth / 2;
      // console.log(this.data.outer_top_margin)
      this.imgTop = self.data.imgViewHeight / 2 - self.imgHeight / 2;
      // console.log('wc',self)
      // setTimeout(function(){
      //设置旋转后的裁剪框
      // console.log(self.imgWidth,self.imgHeight,self.imgLeft,self.imgTop)
      self.setData({
        cutW: self.imgWidth,
        cutH: self.imgHeight,
        cutL: self.imgLeft,
        cutT: self.imgTop
      })
      // console.log(this.data.imgHeight)
      // this.setData({
      //   imgWidth: self.imgWidth,
      //   imgHeight: self.imgHeight,
      //   imgLeft: self.imgLeft,
      //   imgTop: self.imgTop
      // })
      this.data.imgWidth = this.imgWidth;
      this.data.imgHeight = this.imgHeight;
      this.data.imgLeft = this.imgLeft;
      this.data.imgTop = this.imgTop;
      this.setData({
        tempCanvasWidth: this.imgWidth + 5,
        tempCanvasHeight: this.imgHeight + 5,
      })
      // self.openCroper()
      // },700)
    },
    hidecrop(){
      this.setData({
        croped: true
      })
    }
  }
})